<template>
	<!-- <view class="main-class"> -->
	<z-paging ref="paging" v-model="purPlanData" @query="queryList" class="plan-container">
		<template #top>	
			<tn-sticky>
				<view class="header-class">
					<view class="status_bar" style="height: var(--status-bar-height); width: 100%;"></view>			
					<tn-navbar height="45px" home-icon="" :bottom-shadow="false" bg-color="tn-type-primary_bg" text-color="tn-white">
						采购计划清单
						<template #right>
							<view class="add-button" @click="toNavigatePage"> 
								<text class="add-text">新建</text>
							</view>
						</template>
					</tn-navbar>
					<view class="search-box-wrapper">
						<tn-search-box
							v-model="searchValue"
							@input="searchInputEvent"
							@search="searchBtnClickEventPage"
							size="sm"
							placeholder="搜索关键词,检索供应商"
							placeholder-icon="search"
							border-color="#FFFFFF"
							text-color="#FFFFFF"
							placeholder-color="#FFFFFF"
							class="search-box"
							search-button-bg-color="#6bb7ec"
							shape="round"
						/>
					</view>
				</view>
				<view class="date-range" @click="openCalendarPopup">
					<view class="date-picker-title">
						<tn-icon name="calendar" size="32" color="#666666"></tn-icon>
						<text class="picker-text">时间选择</text>
					</view>
					<text class="date-text">{{dataInfo.startDate}} 至 {{dataInfo.endDate}}</text>
				</view>
			</tn-sticky>
		</template>

		<view class="plan-list">
			<view class="plan-item" v-for="(item, index) in purPlanData" :key="item.billcode" @click="toNavigate(item)">
				<view class="plan-header">
					<text class="business-name tn-text-ellipsis-2">{{item.businessname}}</text>
					<text class="plan-status" :class="{'status-warning': item.orderstate === '未审核'}">{{item.orderstate}}</text>
				</view>
				<view class="plan-info">
					<text class="bill-code">{{item.billcode}}</text>
					<text class="plan-date">{{item.dates}}</text>
				</view>
				<view class="plan-summary">
					<view class="variety-count">
						品种数：<text class="highlight-text">{{item.ordernum}}</text>
					</view>
					<view class="amount">
						金额：<text class="highlight-text">{{item.taxamount}}</text>
					</view>
				</view>
				<view class="plan-remark" v-if="item.remark">
					<text class="remark-label">备注：</text>
					<text class="remark-content">{{item.remark}}</text>
				</view>
			</view>
		</view>
	</z-paging>
	<!-- </view> -->
	
	
	
	<tn-popup v-model="showCalendarPopup" open-direction="top" class="popup-class">
		<view class="calendar-wrapper">
			<tn-calendar v-model="selectDate" min-date="2024-01-01" mode="range" class="calendar-class"/>
			<view class="calendar-action">
				<tn-button class="calendar-confirm" @click="closeCalendarPopupPage">
					选择所选日期
				</tn-button>
			</view>
		</view>
	</tn-popup>
	
</template>

<script setup>
	import { ref,reactive,onMounted } from 'vue'
	import { postCall  } from '@/api/index.js'
	import { EventBus } from '@/mitt/EventBus.js';
	import { toastMessage } from '@/utils/toast.js'
	import { createParams } from '@/utils/utils.js'
	import md5 from "js-md5";
	import dayjs from "dayjs";
	import Big from 'big.js';
	
	const procName = "PROC_APP_DO_PURPLAN";
	const selectDate = ref('')
	const searchValue = ref("")
	const currentSwiperIndex = ref(1)
	const currentTabsIndex = ref(0)
	const userInfo = reactive({});
	let index = 0;
	const showCalendarPopup = ref(false)
	
	const openCalendarPopup = () => {
	  showCalendarPopup.value = true
	}
	
	const paging = ref(null)
	
	let pageInfo = {
		P_PAGE : 1 ,
		P_PAGESIZE : 10
	}
	
	const queryList = (pageNo, pageSize) =>{
		pageInfo.P_PAGE = pageNo;
		pageInfo.P_PAGESIZE = pageSize;
		
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "QUERY";
		params["P_CON"] = searchValue.value;
		postCall(Object.assign(Object.assign(params,createParams(dataInfo)),pageInfo)).then(res=>{
			if(res){
				if(res.code===200 || res.code===1000){
							   paging.value.complete(res.data.DATASET);
				}
			}
		  
		}).catch(res =>{
			paging.value.complete(false);
		})
	}
	
	const searchBtnClickEventPage = () =>{
		paging.value.reload();
	}
	
	const closeCalendarPopupPage = () =>{
		showCalendarPopup.value = false;
		let date = {
						"startDate":dayjs(selectDate.value[0]).format('YYYY-MM-DD'),
						"endDate":dayjs(selectDate.value[1]).format('YYYY-MM-DD')
					}
		 Object.assign(dataInfo,date);
		 paging.value.reload();
	}
	
	const closeCalendarPopup = () => {
	  showCalendarPopup.value = false
	  console.log(selectDate.value);
	  let date = {
	  				"startDate":dayjs(selectDate.value[0]).format('YYYY-MM-DD'),
	  				"endDate":dayjs(selectDate.value[1]).format('YYYY-MM-DD')
	  			}
	   Object.assign(dataInfo,date);
	   doGetPurPlan();
	}
	
	const searchInputEvent = ()=>{
		
	}
	const searchBtnClickEvent = ()=>{
		
	}
	const dataInfo = reactive({"startDate":"2024-01-01","endDate":"2024-04-31"})
	let loginInfo = {};
	
	onMounted(()=>{
		
		const firstDayOfMonth = dayjs().startOf('month');
		let date = {
						"startDate":firstDayOfMonth.format('YYYY-MM-DD'),
						"endDate":dayjs().format("YYYY-MM-DD")
					}
		Object.assign(dataInfo,date);
		// doGetPurPlan();
	})
	 
	
	const clickOrder = (val) =>{
		index = val.id;
		// console.log(currentTabsIndex.value);
		doGetOrder();
	 //  uni.setStorageSync("order",val.id)	
	 //  uni.navigateTo({
		// url: val.path
	 //  });
	}
	const purPlanData = ref([]);
	const doGetPurPlan = () =>{
		purPlanData.length = 0;
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "QUERY";
		postCall(Object.assign(params,createParams(dataInfo))).then(res=>{
			if(res){
				if(res.code===200){
							   Object.assign(purPlanData,res.data.DATASET);	   
							   console.log(purPlanData);
				}
			}
		})
	}
	let toNavigatePage = (val) =>{
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_EXPANDLIST";
		params["P_ACTION"] = "CGJHTZ";
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					uni.navigateTo({
						url: '/pages/purplan/plan'
					})
				}else if(res.code===1000){
					toastMessage("暂无权限");
				}
			}
		})
		
	}
	let toNavigate = (val) =>{
		let tempOrderData  = [];
		let convertOrderData = [];
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "DETAIL";
		params["P_BILLNO"] = val.billno;
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
							   Object.assign(tempOrderData,res.data.DATASET);	   
							   // console.log(statusData);
							   const mergedData = tempOrderData.reduce((acc, cur) => {
							       const { billno,billcode, businessname,caozyname, ...rest } = cur;
							       if (!acc[billcode]) {
							           acc[billcode] = { billno,billcode, businessname,caozyname, details: [rest] };
							       } else {
							           acc[billcode].details.push(rest);
							       }
							       return acc;
							   }, {});
							   
							   const businessStats = {};
							   for (const key in mergedData) {
							       const business = mergedData[key];
							       const totalPrice = business.details.reduce((total, item) => new Big(total).plus(new Big(item.sumtaxamount)), 0);
										mergedData[key]["taxamount"] = totalPrice;
								   }
							    for (const key in mergedData) {
							   	    if (Object.hasOwnProperty.call(mergedData, key)) {
									   convertOrderData.push(mergedData[key]);
									}
							     }
								uni.setStorageSync("PURPLANINFO",convertOrderData[0]) 
								uni.navigateTo({
									url: '/pages/purplan/purplandetails'
								})
				}
			}
		   
		})
	}
	
</script>

<style>
.plan-container {
	background-color: #f5f7fa;
}

.header-class {
	background: var(--tn-color-primary);
	padding-bottom: 15rpx;
}

.search-box-wrapper {
	padding: 20rpx 30rpx;
}

.search-box {
	background: rgba(255, 255, 255, 0.15);
	border-radius: 40rpx;
}

.add-button {
	padding: 8rpx 24rpx;
}

.add-text {
	color: #fff;
	font-size: 28rpx;
	padding: 8rpx 24rpx;
	border: 2rpx solid #fff;
	border-radius: 30rpx;
}

.date-range {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: #fff;
	border-bottom: 2rpx solid #f0f0f0;
}

.date-picker-title {
	display: flex;
	align-items: center;
}

.picker-text {
	margin-left: 12rpx;
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
}

.date-text {
	color: #666;
	font-size: 28rpx;
}

.plan-list {
	padding: 20rpx;
}

.plan-item {
	background: #fff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.plan-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 20rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.business-name {
	flex: 1;
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	padding-right: 20rpx;
}

.plan-status {
	font-size: 28rpx;
	color: var(--tn-color-primary);
	font-weight: bold;
}

.status-warning {
	color: #ff9900;
}

.plan-info {
	display: flex;
	justify-content: space-between;
	padding: 20rpx 0;
	font-size: 28rpx;
}

.bill-code {
	color: #666;
}

.plan-date {
	color: #999;
}

.plan-summary {
	display: flex;
	justify-content: space-between;
	padding: 20rpx 0;
	border-top: 2rpx solid #f0f0f0;
	font-size: 28rpx;
}

.highlight-text {
	color: #ff6b6b;
	font-weight: 500;
	margin-left: 8rpx;
}

.plan-remark {
	padding: 20rpx 0;
	font-size: 28rpx;
	color: #666;
	border-top: 2rpx solid #f0f0f0;
}

.remark-label {
	color: #999;
}

.remark-content {
	color: #666;
}

.popup-class {
	border-radius: 20rpx 20rpx 0 0;
	overflow: hidden;
}

.calendar-wrapper {
	background: #fff;
	padding: 30rpx 0;
}

.calendar-class {
	height: 100% !important;
}

.calendar-action {
	padding: 20rpx 30rpx;
}

.calendar-confirm {
	width: 100%;
	height: 80rpx;
	border-radius: 40rpx;
	font-size: 30rpx;
	font-weight: 500;
}
</style>
